package com.phy.gsjl.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.SessionAttributes;

import com.phy.gsjl.entity.User;
import com.phy.gsjl.service.IUserService;
import com.phy.gsjl.util.PasswordHelper;

/**
 * 登录控制器
 * 
 * @author curry
 *
 */
@Controller
@RequestMapping("/phy")
@SessionAttributes(value = { "user" })
public class LoginController {

	@Autowired
	public IUserService userServiceImpl;

	//获取日志对象
	private static Logger logger = Logger.getLogger(LoginController.class);
		
	/**
	 * 登录
	 * 
	 * @param username
	 * @param password
	 * @return
	 */
	@RequestMapping("/login")
	public String dologin(String username, ModelMap map) {
		//前台已经验证账户密码，此处将登录用户信息加入session域中
		logger.info("==>login info of username: " + username);
		User user = userServiceImpl.getUserByName(username);
		map.addAttribute("user", user);
		return "manage";
	}

	@ResponseBody
	@RequestMapping("/loginverify")
	public String doverify(String username, String password) {
		logger.info("==>loginverify info of username: " + username + " password: " + password);
		User user = userServiceImpl.getUserByName(username);
		logger.info("==>is user null:" + (user == null));
		//处理ajax请求验证账号密码
		if (user != null && user.getPassword().equals(PasswordHelper.encryptToMD5(password))) {
			return "success";
		} else {
			return "error";
		}
	}

	/**
	 * @ModelAttribute("User")相当于将session中名为"User"的对象注入user对象中
	 * sessionStatus中的setComplete方法可以将session中的内容全部清空
	 * 
	 * @param user
	 * @param sessionStatus
	 * @return
	 */
	@RequestMapping("/logout")
	public String dologout(HttpSession session) {
		logger.info("==>info of the session id:" + session.getId());
		session.removeAttribute("user");//退出系统，将session清除，然后重定向至登录界面
		return "redirect:/login.html";
	}
	
	/**
	 * 获取session，ajax请求用户数据通过这里获取
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/getsession")
	public User dogetSession(HttpServletRequest request){
		User user =(User) request.getSession().getAttribute("user");
		return user;
	}
}
